<?php

namespace app\rent\controller\Product;

use think\Controller;
use think\Db;

class Lease extends Controller
{
    protected $LeaseModel = null;
    protected $BusinessModel = null;
    protected $ProductModel = null;
    protected $RecordModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->LeaseModel = model('Product.Lease');
        $this->BusinessModel = model('Business.Business');
        $this->ProductModel = model('Product.Product');
        $this->RecordModel = model('Business.Record');
    }

    public function add()
    {
        $params = $this->request->param();

        $product = $this->ProductModel->find($params['proid']);

        if (!$product) {
            $this->error('租赁商品不存在');
        }

        $business = $this->BusinessModel->find($params['busid']);

        if (!$business) {
            $this->error('用户不存在');
        }

        if ($business['auth'] == 0) {
            $this->error('邮箱未认证，请先认证');
        }

        $UpdateMoney = bcsub($business['money'], $params['price']);

        if ($UpdateMoney < 0) {
            $this->error('余额不足，请先充值');
        }

        // 开启事务
        Db::startTrans();

        // 封装租赁订单数据
        $LeaseData = [
            'busid' => $params['busid'],
            'proid' => $params['proid'],
            'rent' => $params['rent'],
            'price' => $params['price'],
            'starttime' => $params['starttime'],
            'endtime' => $params['endtime'],
            'address' => $params['address'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district'],
            'status' => 1
        ];

        $card = build_upload('card');

        if ($card['code'] === 0) {
            $this->error($card['msg']);
        }

        $LeaseData['card'] = $card['data'];

        $LeaseStatus = $this->LeaseModel->validate('common/Product/Lease')->save($LeaseData);

        if ($LeaseStatus === FALSE) {
            $this->error($this->LeaseModel->getError());
        }

        /* 
            商品的库存 如果租出去了就需要扣库存，注意归还商品的库存加回去（暂不做）
        */

        // 更新用户余额
        $BusinessData = [
            'id' => $business['id'],
            'money' => $UpdateMoney
        ];

        $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

        if ($BusinessStatus === FALSE) {
            $this->error('用户余额更新失败');
        }

        // 消费记录
        $ProductName = $product['name'];
        $day = $params['day'];

        // 插入消费记录
        $RecordData = [
            'total' => "-{$params['price']}",
            'content' => "您租赁了【{$ProductName}】 $day 天，消费了{$params['price']}元",
            'busid' => $params['busid']
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

        if ($RecordStatus === FALSE) {
            $this->error($this->RecordModel->getError());
        }

        if ($LeaseStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE) {
            Db::rollback();
            if (isset($LeaseData['card']) && $_FILES['card']['size'] > 0) {
                @is_file('.' . $LeaseData['card']) && @unlink('.' . $LeaseData['card']);
            }

            $this->error('租赁失败');
        } else {
            Db::commit();
            $this->success('租赁成功');
        }
    }
}
